package com.cq.school.service;

import com.cq.school.entity.Apply;
import com.cq.school.repository.ApplyDao;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User:oa3158
 * Date: 13-12-12
 * Time: 上午11:06
 * To change this template use File | Settings | File Templates.
 */
@Component
@Transactional
public class ApplyService {
    @Autowired
    private ApplyDao applyDao;

    public Page<Apply> listApply(Long schoolId, int pageNumber, int pageSize){
        Specification<Apply> spec = buildSpecification(schoolId);
        return applyDao.findAll(spec,new PageRequest(pageNumber - 1, pageSize, new Sort(Sort.Direction.DESC, "id")));
    }

    public List<Apply> listApply(long schoolId)
    {
       return applyDao.findAll(buildSpecification(schoolId));
    }

    /**
     * 创建动态查询条件组合.
     */
    private Specification<Apply> buildSpecification(Long schoolId) {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        if(schoolId!=null&&schoolId>0)
            filters.put("schoolId", new SearchFilter("schoolId", SearchFilter.Operator.EQ, schoolId));
        return DynamicSpecifications.bySearchFilter(filters.values(), Apply.class);
    }

    public void saveApply(Apply apply){
        if(apply.getId()==null)
            apply.setCreateTime(new Date());
        applyDao.save(apply);
    }
}
